-- @Author: baidwwy
-- @Date:   2018-04-10 22:48:47
-- @Last Modified by:   baidwwy
-- @Last Modified time: 2018-08-18 19:48:56
--================================================================
--全局
--================================================================
function gge.ARGB(a,r,g,b)
    return bit.bor(bit.lshift(a,24) , bit.lshift(r,16) , bit.lshift(g,8) , b)
end
function gge.RGB(r,g,b)
    return ARGB(255,r,g,b)
end
--泛型
function gge.mpairs(t)
    local i = 0
    local m = table.maxn(t)
    return function ()
        repeat
            i=i+1
            if t[i] then return i,t[i] end
        until i>=m
    end
end
function gge.pairsi(t)--泛型倒序
    local i = #t+1
    return function ()
        i=i-1
        if i>=1 then
            return i,t[i]
        end
    end
end
function gge.splitchar(str)--泛型分割字符
    local i = 0
    local ascii = 0
    return function ()
        i = i+1
        ascii = string.byte(str, i)
        if ascii then
            if ascii < 127 then
                return 1,string.sub(str, i, i)
            else
                i = i+1
                return 2,string.sub(str, i-1, i)
            end
        else
            return nil
        end
    end
end
gge.分割文本 = string.split
function gge.是否邮箱( str)
    return str:match("[%d%a]+@%a+.%a+")==str
end
function gge.删首尾空( str )
    return str:match("%s*(.-)%s*$")
end

function gge.enip(ip)--IP地址转整数IP
    local c = string.split(ip,".")
    return bit.bor(bit.lshift(c[1], 24),bit.lshift(c[2], 16),bit.lshift(c[3], 8),c[4])
end
function gge.deip(int)--整数IP转到文本地址
    local ip = {
        bit.rshift(int, 24),
        bit.band(bit.rshift(int, 16),255),
        bit.band(bit.rshift(int, 8),255),
        bit.band(int,255)
    }
    return table.concat( ip, ".")
end
function gge.取拼音首字母(str)
    local i,b,r = 1,0,''
    while true do
        b = str:byte(i)
        if b then
            if b < 127 then
                r = r .. str:sub(i, i)
                i = i+1
            else
                local c = bit.bor(bit.lshift(b, 8),str:byte(i+1))
                if c>=0xB0A1 and c<=0xB0C4 then r = r .. 'a';
                    elseif c>=0XB0C5 and c<=0XB2C0 then r = r .. 'b';
                    elseif c>=0xB2C1 and c<=0xB4ED then r = r .. 'c';
                    elseif c>=0xB4EE and c<=0xB6E9 then r = r .. 'd';
                    elseif c>=0xB6EA and c<=0xB7A1 then r = r .. 'e';
                    elseif c>=0xB7A2 and c<=0xB8c0 then r = r .. 'f';
                    elseif c>=0xB8C1 and c<=0xB9FD then r = r .. 'g';
                    elseif c>=0xB9FE and c<=0xBBF6 then r = r .. 'h';
                    elseif c>=0xBBF7 and c<=0xBFA5 then r = r .. 'j';
                    elseif c>=0xBFA6 and c<=0xC0AB then r = r .. 'k';
                    elseif c>=0xC0AC and c<=0xC2E7 then r = r .. 'l';
                    elseif c>=0xC2E8 and c<=0xC4C2 then r = r .. 'm';
                    elseif c>=0xC4C3 and c<=0xC5B5 then r = r .. 'n';
                    elseif c>=0xC5B6 and c<=0xC5BD then r = r .. 'o';
                    elseif c>=0xC5BE and c<=0xC6D9 then r = r .. 'p';
                    elseif c>=0xC6DA and c<=0xC8BA then r = r .. 'q';
                    elseif c>=0xC8BB and c<=0xC8F5 then r = r .. 'r';
                    elseif c>=0xC8F6 and c<=0xCBF9 then r = r .. 's';
                    elseif c>=0xCBFA and c<=0xCDD9 then r = r .. 't';
                    elseif c>=0xCDDA and c<=0xCEF3 then r = r .. 'w';
                    elseif c>=0xCEF4 and c<=0xD1B8 then r = r .. 'x';
                    elseif c>=0xD1B9 and c<=0xD4D0 then r = r .. 'y';
                    elseif c>=0xD4D1 and c<=0xD7F9 then r = r .. 'z';
                else
                    r = r .. '?'
                end
                i = i+2
            end
        else
            break
        end
    end
    return r
end
function gge.路径_去除扩展名(str)
    local idx = str:match(".+()%.%w+$")
    if(idx) then
        return str:sub(1, idx-1)
    else
        return str
    end
end
function gge.路径_取文件名(str)
    return string.match(str:gsub("/","\\"), ".+\\([^/]*%.%w+)$")
end
function gge.路径_取扩展名(str)
    return str:match(".+%.(%w+)$")
end
function gge.格式化货币(n) -- credit http://richard.warburton.it
    local left,num,right = string.match(n,'^([^%d]*%d)(%d*)(.-)$')
    return left..(num:reverse():gsub('(%d%d%d)','%1,'):reverse())..right
end
-- --解码
-- function gge.decodeURI(s)
--     s = string.gsub(s, '%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end)
--     return s
-- end

-- --加码
-- function gge.encodeURI(s)
--     s = string.gsub(s, "([^%w%.%- ])", function(c) return string.format("%%%02X", string.byte(c)) end)
--     return string.gsub(s, " ", "+")
-- end
--================================================================
--table
--================================================================
    --表序列化
    table.tostring = function (t)
        if t then
            local mark      ={}
            local assign    ={}
            local function ser_table(tbl,parent)
                mark[tbl]=parent
                local tmp={}
                for k,v in pairs(tbl) do
                    local key
                    if type(k) == "number" then
                        key = "["..k.."]"
                    elseif tonumber(k) ~= nil then
                        key = "[".. string.format("%q", k) .."]"
                    else
                        key = k
                    end
                    if type(v) == "string" then
                        table.insert(tmp, key.."=".. string.format("%q", v))
                    elseif type(v) == "number" or type(v) == "boolean" then
                        table.insert(tmp, key.."=".. tostring(v))
                    elseif type(v)=="table" then
                        local dkey = type(k)=="number" and "["..k.."]" or "[".. string.format("%q", k) .."]"
                        local dotkey = parent.. dkey
                        if mark[v] then
                            table.insert(assign,dotkey.."="..mark[v])
                        else
                            table.insert(tmp, key.."="..ser_table(v,dotkey))
                        end
                    end
                end
                return "{"..table.concat(tmp,",").."}"
            end
            return ser_table(t,"ret")..table.concat(assign,";")
        end
    end
    --载入序列化表
    table.loadstring = function (t)
        if t and type(t) == 'string' then--兼容
            local f = loadstring(t:byte() == 100 and t or ("do local ret="..t.." return ret end"))
            if f then
                setfenv(f, {})
                return f()
            end
        end
        --return {}
    end
    --表复制
    table.copy = function (old_tab)
        local new_tab = {};
        if old_tab and type(old_tab)=='table' then
            for i,v in pairs(old_tab) do
                local vtyp = type(v);
                if (vtyp == "table") then
                    new_tab[i] = table.copy(v);
                elseif (vtyp == "string" or vtyp == "number" or vtyp == "boolean") then
                    new_tab[i] = v;
                else
                    error("不支持复制")
                end
            end
        end
        return new_tab;
    end
    --表打印
    table.print = function (root)
        if root then
            local print = print
            local tconcat = table.concat
            local tinsert = table.insert
            local srep = string.rep
            local type = type
            local pairs = pairs
            local tostring = tostring
            local next = next
            local cache = {  [root] = "." }
            local function _dump(t,space,name)
                local temp = {}
                if next(t) then
                    tinsert(temp,"{")
                    for k,v in pairs(t) do
                        local key = tostring(k)
                        if cache[v] then
                            tinsert(temp,"\t" .. key .. "={" .. cache[v].."}")
                        elseif type(v) == "table" then
                            local new_key = name .. "." .. key
                            cache[v] = new_key
                            tinsert(temp,"\t" .. key .. "=".._dump(v,space .. srep("\t",#key),new_key))
                        else
                            tinsert(temp,"\t" .. key .. "=" .. tostring(v))
                        end
                    end
                    tinsert(temp,"}")
                else
                    tinsert(temp,"{}")
                end

                return tconcat(temp,"\n"..space)
            end
            print('-------------------------------------')
            print(root)
            print(_dump(root,"",""))
            print('-------------------------------------')
        end
    end
    table.removeall = function ( t )
        for k in pairs(t) do
            t[k] = nil
        end
    end
--================================================================
--string
--================================================================
    --按分割每个字,添加到表
    function string.splitchar(str,tv)
        local t = tv or {}
        local i = 1
        local ascii = 0
        while true do
            ascii = string.byte(str, i)
            if ascii then
                if ascii < 127 then
                    table.insert(t,string.sub(str, i, i))
                    i = i+1
                else
                    table.insert(t,string.sub(str, i, i+1))
                    i = i+2
                end
            else
                break
            end
        end
        return t
    end
    --分割文本(文本,分割符)
    string.split = function (str, mark)
        if str  then
            local result = {}
            if mark == '%' then
                mark = "([^"..mark.."%]+)"
            else
                mark = "([^"..mark.."]+)"
            end
            for match in tostring(str):gmatch(mark) do
                table.insert(result, match)
            end
            return result
        end
        return {}
    end
--================================================================
--math
--================================================================
    --只适合小数四舍五入(数值,小数位)
    math.round = function (num, idp)
      return tonumber(string.format("%." .. (idp or 0) .. "f", num))
    end
    --适合小数和整数
    math.iround = function (num, idp)
        local mult = 10^(idp or 0)
        return math.floor(num * mult + 0.5) / mult
    end
--================================================================
--os
--================================================================
    --复制文件
    function os.copyfile(old,new)
        local rf = io.open(old,"rb")
        if rf then
            if os.access(new) and not os.remove(new) then
                return false
            end
            local wf = io.open(new,"wb")
            if wf then
                wf:write(rf:read("*all"))
                rf:close()
                wf:close()
                return true
            end
        end
        return false
    end
    --判断文件是否存在
    function os.access(file)
        local rf = io.open(file,"rb")
        if rf then
            rf:close()
            return true
        end
        return false
    end
    --创建目录
    function os.mkdir(file)
        return os.execute("mkdir "..file:gsub('/','\\').." >nul 2>nul")
    end

return gge